package cse3311.calendarapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.UUID;

public class Calendar implements Serializable {
	private static final long serialVersionUID = -3085060522154283565L;
	private ArrayList<Event> events_m;
	private Event[][] timeSlots_m;

	private Calendar() {
		events_m = new ArrayList<Event>();
		timeSlots_m = new Event[365][24];
	}

	private static Calendar instance_m = null;

	public static void initialize() {
		instance_m = new Calendar();
	}

	public static Calendar getCalendar() {
		return instance_m;
	}

	public static void setInstance(Calendar instance) {
		instance_m = instance;
	}

	public String addEvent(EventData data) {
		data.id_m = UUID.randomUUID();

		Event event = new Event(data);

		int hour = data.start_m.get(GregorianCalendar.HOUR_OF_DAY);
		int day = data.start_m.get(GregorianCalendar.DAY_OF_YEAR) - 1;

		if (isTimeSlotAvailable(day, hour)) {
			if (events_m.add(event)) {
				timeSlots_m[day][hour] = event;
				//StorageManager.updateGroupTimeSlots("Team3", day, hour, true);
				return "Event added";
			} else {
				return "Event not added";
			}
		} else {
			return "Time slot not available";
		}
	}

	private boolean isTimeSlotAvailable(int day, int hour) {
		return timeSlots_m[day][hour] == null;
	}

	public EventData editEvent(UUID id) {
		for (Event event : events_m) {
			if (event.getEventData().id_m.equals(id)) {
				return event.getEventData();
			}
		}

		return null;
	}

	public String deleteEvent(UUID id) {
		Event delete = null;
		for (Event event : events_m) {
			if (event.getEventData().id_m.equals(id)) {
				delete = event;
			}
		}
		if (delete != null && events_m.remove(delete)) {
			int hour = delete.getEventData().start_m
					.get(GregorianCalendar.HOUR_OF_DAY);
			int day = delete.getEventData().start_m
					.get(GregorianCalendar.DAY_OF_YEAR) - 1;
			timeSlots_m[day][hour] = null;
			//StorageManager.updateGroupTimeSlots("Team3", day, hour, false);
			return "Event deleted";
		} else {
			return "Event not deleted";
		}
	}

	public String saveEvent(EventData data) {
		for (Event event : events_m) {
			if (event.getEventData().id_m.equals(data.id_m)) {
				event.setEventData(data);
				return "Event saved";
			}
		}

		return "Event not saved";
	}

	public ArrayList<Event> getEvents() {
		return events_m;
	}

	public EventData[] getEventsForDate(GregorianCalendar date) {
		int day = date.get(GregorianCalendar.DAY_OF_YEAR) - 1;
		EventData[] data = new EventData[24];

		for (int i = 0; i < 24; i++) {
			if (timeSlots_m[day][i] != null) {
				data[i] = timeSlots_m[day][i].getEventData();
			} else {
				data[i] = null;
			}
		}

		return data;
	}
}
